﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace 异步编程基础_03
{
    public class MyTasks
    {
        public async Task Method1Async() { await Task.Delay(500); }
        public async Task<String> Method1Async(String s) { await Task.Delay(100); return s; }
        public async Task<int> Method2Async() { var range = Enumerable.Range(1, 1000); int n = range.Sum(); await Task.Delay(0); return n; }
        public async Task<Tuple<int, int>> Method3Async(int n1, int n2) { var result = Tuple.Create(n1 / n2, n1 % n2); await Task.Delay(0); return result; }
        public async Task<double> GetAverageAsync(int arrayLength)
        {
            Random r = new Random();
            int[] nums = new int[arrayLength];
            for (int i = 0; i < nums.Length; i++)
            {
                nums[i] = r.Next();
            }
            await Task.Delay(0);
            return nums.Average();
        }
    }
    class Program
    {
        static MyTasks t = new MyTasks();
        private static int i = 0;

        static void Main(string[] args)
        {
            DoWorkAsync().Wait();

        }

        private static async Task DoWorkAsync()
        {
            Console.WriteLine("开始执行任务...");
            Stopwatch st = new Stopwatch();
            st.Start();
            await t.Method1Async();
            long x = st.ElapsedMilliseconds;
            Console.WriteLine("任务1执行完毕，用时:" + x + "亳秒");
            st.Restart();
            var sum = await t.Method2Async();
            x = st.ElapsedMilliseconds;
            Console.WriteLine("任务2:结果{0}, 用时{1}毫秒", sum, x);
            st.Restart();
            var a1 = await t.Method3Async(39, 8);
            x = st.ElapsedMilliseconds;
            Console.WriteLine("任务3:商{0}, 余数{1},用时{2}亳秒", a1.Item1, a1.Item2, x);
            st.Restart();
            var a2 = await t.GetAverageAsync((20000000));
            x = st.ElapsedMilliseconds;
            Console.WriteLine("产生2千万个随机数并计算其平均值{0}，用时: {1}亳秒", a2, x);
            st.Stop();
            while (i <= 10)
            {
                Console.Write(await t.Method1Async("a "));
                Console.Write(await t.Method1Async("b "));
                i++;
            }
            Console.WriteLine(" \n任务执行完毕");
            Console.ReadKey();
        }

    }
}
